package com.example.musicplayer.fragment

import android.media.MediaPlayer
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.musicplayer.R
import com.example.musicplayer.adapter.MusicAdapter
import com.example.musicplayer.adapter.MusicAdapter.OnMusicClickListener
import com.example.musicplayer.model.Music
import java.io.IOException

class PlaylistFragment
    (
    private val musicTitleTextView: TextView,
    private val musicSingerTextView: TextView,
    private val musicCoverImageView: ImageView,
    private val playPauseButton: ImageView,
    private val musicList: List<Music>,
    private val musicPlayerFragment: MusicPlayerFragment
) : Fragment() {
    private var mediaPlayer: MediaPlayer? = null
    private var currentMusicIndex: Int = -1
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val musicPlayer = inflater.inflate(R.layout.activity_music_player, container, false)

        val musicRecyclerView = musicPlayer.findViewById<RecyclerView>(R.id.music_list)
        musicRecyclerView.layoutManager = LinearLayoutManager(context)

        val adapter = MusicAdapter(musicList, object : OnMusicClickListener {
            override fun onMusicClick(music: Music?) {
                if (music != null) {
                    currentMusicIndex = musicList.indexOf(music) // 确定当前播放的音乐的下标
                    playMusic(music)
                }
            }
        })

        musicRecyclerView.adapter = adapter
        return musicPlayer
    }

    /**
     * 播放音乐
     */
    private fun playMusic(music: Music) {
        try {
            if (mediaPlayer == null) {
                mediaPlayer = MediaPlayer()
            } else {
                mediaPlayer!!.reset()
            }

            mediaPlayer!!.setDataSource(music.src)

            mediaPlayer!!.prepareAsync()

            mediaPlayer!!.setOnPreparedListener {
                mediaPlayer!!.start()
                updateMusicInfo(music)
                updatePlayPage(music, mediaPlayer!!)
            }
        } catch (e: IOException) {
            System.err.println(e.message)
        }
    }

    /**
     * 下一首
     */
    fun nextMusic() {
        // 检查是否有下一首音乐
        if (currentMusicIndex + 1 < musicList.size) {
            currentMusicIndex++
        } else {
            currentMusicIndex = 0 // 第一首
        }
        musicPlayerFragment.pauseCoverImageRotation()
        playMusic(musicList[currentMusicIndex])
    }

    /**
     * 更新播放页面
     */
    private fun updatePlayPage(music: Music, mediaPlayer: MediaPlayer) {
        musicPlayerFragment.updatePlayerPage(music, mediaPlayer)
    }

    /**
     * 更新底部信息
     */
    private fun updateMusicInfo(music: Music) {
        musicTitleTextView.text = music.title
        musicSingerTextView.text = music.singer
        Glide.with(requireContext())
            .load(music.coverImgUrl)
            .placeholder(R.drawable.ic_launcher_background)
            .into(musicCoverImageView)

        playPauseButton.setImageResource(
            if (mediaPlayer != null && mediaPlayer!!.isPlaying) android.R.drawable.ic_media_pause else android.R.drawable.ic_media_play
        )

        playPauseButton.setOnClickListener {
            if (mediaPlayer != null) {
                if (mediaPlayer!!.isPlaying) {
                    mediaPlayer!!.pause()
                    musicPlayerFragment.pauseCoverImageRotation()
                    playPauseButton.setImageResource(android.R.drawable.ic_media_play)
                } else {
                    mediaPlayer!!.start()
                    musicPlayerFragment.startUpdatingSeekBar()  // 更新进度条
                    musicPlayerFragment.resumeCoverImageRotation()
                    playPauseButton.setImageResource(android.R.drawable.ic_media_pause)
                }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (mediaPlayer != null) {
            mediaPlayer!!.release() // 释放资源
            mediaPlayer = null
        }
    }
}